package com.jxc.jxc01.hch.filter;

import com.jxc.jxc01.hch.entity.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.Arrays;

public class LoginFilter implements Filter {
    String [] login;
    String [] power = new String[]{"list.user","delete.inventory","update.WareHouse","delete.WareHouse","increase.WareHouse",
            "delete.user","reductionPassword.user","modify.user","increase.user"};
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
            login = filterConfig.getInitParameter("login").split(",");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        //获取请求路径
        String uri = req.getRequestURI();
        //截取uri路径
        uri = uri.substring(uri.lastIndexOf("/") + 1);

        //判断uri是否在数组定义的不检测uri范围之内
        for(int i=0;i<login.length;i++){
            if(login[i].equals(uri)){
                //放过请求不拦截
                filterChain.doFilter(req,resp);
                return;
            }
        }
//        //其他的请求都是需要进行登录认证的
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        if(null==user){//登录过,放过请求
            resp.sendRedirect("login.html");
            return;
        }else {//没有登录过，重定向到登录页面
            filterChain.doFilter(req,resp);
        }

//        for (int i=0;i< power.length;i++){
//            if (!(power[i].equals(uri))){
//                filterChain.doFilter(req,resp);
//                return;
//            }
//        }
//        if ("admin".equals(user.getAuthority())){
//            filterChain.doFilter(req,resp);
//            return;
//        }

    }


}
